package com.itheima.w_util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.text.StrBuilder;   
import cn.hutool.core.util.StrUtil;

import java.io.File;
import java.nio.charset.StandardCharsets;
   
/**
   * Boot启动类生成工具
   */   
public class BootStarterGenerator {

    /**
     * 生成Spring Boot启动类
     * @param packageName 包名
     * @param className 类名
     * @param outputPath 输出路径（不包含包路径）
     * @return 生成的文件路径
     */
    public static String generateBootStarter(String packageName, String className, String outputPath) {
        // 校验参数
        if (StrUtil.isBlank(packageName) || StrUtil.isBlank(className) || StrUtil.isBlank(outputPath)) {
            throw new IllegalArgumentException("参数不能为空");
        }

        // 构建包路径
        String packagePath = packageName.replace(StrUtil.toString(File.separatorChar), ".");
        String fullOutputPath = outputPath + File.separator + packageName;
        
        // 确保目录存在
        FileUtil.mkdir(fullOutputPath);

        // 构建文件内容
        String content = buildClassContent(packagePath, className);

        // 写入文件
        String filePath = StrUtil.join(File.separator,fullOutputPath,className+".java");
        FileUtil.writeString(content, filePath, StandardCharsets.UTF_8);

        return filePath;
    }

    /**
     * 构建类内容
     */
    private static String buildClassContent(String packageName, String className) {
        StrBuilder sb = StrBuilder.create();
        
        // 包声明
        sb.append("package ").append(packageName).append(";\n\n");
        
        // 导入语句
        sb.append("import org.springframework.boot.SpringApplication;\n");
        sb.append("import org.springframework.boot.autoconfigure.SpringBootApplication;\n\n");
        
        // 类注释
        sb.append("/**\n");
        sb.append(" * ").append(className).append(" - Spring Boot启动类\n");
        sb.append(" */\n");
        
        // 类定义
        sb.append("@SpringBootApplication\n");
        sb.append("public class ").append(className).append(" {\n\n");
        
        // main方法
        sb.append("    public static void main(String[] args) {\n");
        sb.append("        SpringApplication.run(").append(className).append(".class, args);\n");
        sb.append("    }\n\n");
        
        // 类结束
        sb.append("}\n");
        
        return sb.toString();
    }

    // 示例用法
    public static void main(String[] args) {
        String packageName = "com.example.demo";
        String className = "DemoApplication";
        String outputPath = "D:\\selfData\\studynote\\code-util\\src\\test\\java";
        
        String filePath = generateBootStarter(packageName, className, outputPath);
        System.out.println("启动类已生成: " + filePath);
    }   
}
